package com.example.victory.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 进程运行辅助类
 */
public class ProcessHelper {
    private static final Logger logger = LoggerFactory.getLogger(ProcessHelper.class);

    public static int run(String command, boolean isLog) {
        if (StringUtils.isEmpty(command)) {
            logger.error("ProcessHelper.run failed,command is empty");
            return -1;
        }

        logger.info("运行进程：{}", command);
        int result = 0;
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            //从命令行打印出输出结果
            String line = null;
            boolean isFirst = true;
            while ((line = stdInput.readLine()) != null) {
                if (isFirst && isLog) {
                    logger.info("运行日志：");
                    isFirst = false;
                }
                if (isLog) {
                    logger.info(line);
                }
            }

            isFirst = true;
            while ((line = stdError.readLine()) != null) {
                if (isFirst) {
                    logger.info("运行错误：");
                    isFirst = false;
                }
                logger.error("", line);
            }

            result = process.waitFor();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = -1;
        }
        return result;
    }
}
